import { Injectable } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'

import { FieldBase } from './field-base.interface'

@Injectable()
export class FieldControlService {
  constructor() {}

  toFormGroup(fields: FieldBase<any>[]): FormGroup {
    const group: any = {}
    fields.forEach(field => {
      switch (field.controlType) {
        case 'group':
          group[field.key] = this.toFormGroup(field['fields'])
          break
        default:
          const validators = field.validators && field.validators.length ? field.validators : null
          const formState = {
            value: field.value === 0 ? field.value : ( field.value || '' ),
            disabled: field.disabled,
          }
          group[field.key] = new FormControl(formState, validators, null)
      }
    })
    return new FormGroup(group)
  }
}
